<template>
  <a-tree-select
    :tree-default-expanded-keys="expandedKeys"
    :value="selectValue"
    :tree-data="treeData"
    allow-clear
    :multiple="multiple"
    placeholder="请选择"
    tree-node-filter-prop="pathName"
    :field-names="{
      label: 'pathName',
      key: 'id',
      value: 'id'
    }"
    :dropdown-style="{ minWidth: '220px' }"
    @focus="onFocus"
    @change="onChange"
    @select="onSelect"
  >
    <template v-if="loading" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-tree-select>
</template>

<script setup>
/**
 * @name:选择客户来源
 */
import { ref, onMounted } from 'vue'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'

const loading = ref(true)
const options = ref([])
const expandedKeys = ref(['0'])
const selectValue = ref()
const emit = defineEmits(['update:value', 'change'])
const props = defineProps({
  value: {
    type: [String, Array],
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: false
  },
  trigger: {
    desc: '请求数据时机init:初始化/focus:聚焦',
    type: String,
    default: 'init'
  }
})

const onChange = (value, option) => {
  // if (props.multiple) {
  selectValue.value = value
  emit('update:value', value)
  emit('change', value, option)
  // }
}
const onSelect = (value, node) => {
  if (!props.multiple) {
    emit('update:value', value)
    emit('change', value, node)
    nextTick(() => {
      selectValue.value = node.pathNameStr
    })
  }
}
const treeData = ref([])
// 获取数据
const getData = async () => {
  loading.value = true
  if (options.value.length > 0) return
  const { code, data, defaultCustomPathId = null } = await post('/operation/opex/getCustomPathListV2', {})
  loading.value = false
  if (code !== 0) return
  treeData.value = [{ id: '0', pathName: getSystemConfig('HISNAME'), children: generatePathNameStr(data?.trees) }] //系统名称
  if (defaultCustomPathId) {
    selectValue.value = defaultCustomPathId
    const result = findItemByField(treeData.value, 'id', selectValue.value)
    if (result) {
      emit('update:value', selectValue.value)
      emit('change', selectValue.value, result)
      nextTick(() => {
        selectValue.value = result.pathNameStr
      })
    }
  }
}

// 获取满足条件的第一个
function findItemByField(arr, fieldName, value) {
  for (const item of arr) {
    // 如果当前项满足条件，直接返回该项
    if (item[fieldName] === value) {
      return item
    }
    // 如果当前项有 children，则递归查找
    if (Array.isArray(item.children)) {
      const foundInChildren = findItemByField(item.children, fieldName, value)
      if (foundInChildren) {
        return foundInChildren
      }
    }
  }
  // 如果没有找到符合条件的项，返回 null
  return null
}

function generatePathNameStr(items, parentPath = '') {
  return items.map((item) => {
    const newItem = { ...item, disabled: item.status === '1' } // 浅复制当前项
    const currentPath = `${parentPath}${parentPath ? '/' : ''}${newItem.pathName}` // 构建当前路径
    newItem.pathNameStr = currentPath // 将路径字符串添加到当前项

    // 如果当前项有子项，则递归调用函数
    if (newItem.children) {
      newItem.children = generatePathNameStr(newItem.children, currentPath)
    }

    return newItem
  })
}
function findByName(items, id) {
  for (let i = 0; i < items.length; i++) {
    if (items[i].id === id) {
      return items[i] // 如果找到，返回该项
    }
    if (items[i].children) {
      const found = findByName(items[i].children, id) // 递归查找子项
      if (found) {
        return found // 如果在子项中找到，返回该项
      }
    }
  }

  return null // 如果没有找到，返回 null
}

const initSelectValue = (id) => {
  selectValue.value = findByName(treeData.value, id)?.pathNameStr
}
watch(
  () => [props.value, treeData.value],
  () => {
    props.value && treeData.value.length && initSelectValue(props.value)
  }
)

const onFocus = () => {
  props.trigger === 'focus' && getData()
}
onMounted(() => {
  props.trigger === 'init' && getData()
})
</script>
